package com.example.demo.advice;

import com.example.demo.dto.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 错误路径处理
 */
@RestController
@RequestMapping("${server.error.path:${error.path:/error}}")
@Slf4j
public class MyErrorController implements ErrorController {

    @Autowired
    private ErrorAttributes errorAttributes;


    @RequestMapping
    public ResponseResult doHandleError(HttpServletRequest request, WebRequest webRequest, HttpServletResponse response) {
        Map<String, Object> attributes = this.errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults());
        log.error("进入错误路径处理方法：{}", attributes.get("path"));
        int status = response.getStatus();
        return ResponseResult.build(1, status, "服务器错误", MDC.get("traceId"));
    }

}